package com.ggdog.blog.Services.impl;

import com.ggdog.blog.Services.FileService;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;
@Service
public class FileServiceImpl implements FileService {

    /**
     * 根据用户名和路径生成新UUID文件名
     * @param originalFilename 原始用户名
     * @param userName
     * @param path
     * @return
     */
    @Override
    public String changeFileNameWithPath(String originalFilename,String userName, String path) {
        //使用UUID改文件名

        System.out.println("originalFilename = " + originalFilename);
        String newFileName= String.valueOf(UUID.randomUUID());
        String fileExtension = "";
        // 检查文件名是否为空
        if (originalFilename != null && originalFilename.contains(".")) {
            // 获取文件的扩展名
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            newFileName+="."+fileExtension;
            System.out.println("文件的扩展名是: " + fileExtension);
        } else {
            System.out.println("文件没有扩展名");
        }

        newFileName=userName+"/"+path+"/"+newFileName;
        return newFileName;
    }

    @Override
    public ResponseEntity<String> upload(MultipartFile file,String newFileName,MultiValueMap<String, Object> body) {
        // 目标 URL
        String targetUrl = "http://211.101.233.71:8083/netdisk/api/upload";
//        String targetUrl = "http://localhost:8083/netdisk/api/upload";


        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 创建 HttpEntity 封装请求头和请求体
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();

        // 发送 POST 请求到目标服务器
        ResponseEntity<String> response = restTemplate.exchange(targetUrl, HttpMethod.POST, requestEntity, String.class);
        String newResBody=response.getBody().substring(0,response.getBody().length()-1)+",\"newFileName\":\""+newFileName+"\"}";
        System.out.println(newResBody);
        ResponseEntity<String> response1=new ResponseEntity<>(newResBody,response.getStatusCode());

        // 返回响应内容
        return response1;
    }
}
